package linda.server;

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Collection;

import linda.Callback;
import linda.Linda;
import linda.Tuple;
import linda.server.InterfaceServer.method;

/**
 * Client part of a client/server implementation of Linda. It implements the
 * Linda interface and propagates everything to the server it is connected to.
 * */
public class LindaClient implements Linda {

	private InterfaceServer server;

	/**
	 * Initializes the Linda implementation.
	 * 
	 * @param serverURI
	 *            the URI of the server, e.g. "//localhost:4000/LindaServer".
	 */
	public LindaClient(String serverURI) {
		try {	
			//server = (InterfaceServer) Naming.lookup("rmi://" + serverURI + ":1099/ServerLinda");
			Registry reg = LocateRegistry.getRegistry(serverURI);
			server = (InterfaceServer) reg.lookup("ServerLinda");
		} catch (Exception e) {
			System.err.println(e);
		}
	}

	public void write(Tuple t) {
		try {
			server.DoWork(method.WRITE, t);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	public Tuple take(Tuple template) {
		try {
			return (Tuple) server.DoWork(method.TAKE, template);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Tuple read(Tuple template) {
		try {
			return (Tuple) server.DoWork(method.READ, template);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Tuple tryTake(Tuple template) {
		try {
			return (Tuple) server.DoWork(method.TRYTAKE, template);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Tuple tryRead(Tuple template) {
		try {
			return (Tuple) server.DoWork(method.TRYREAD, template);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Collection<Tuple> takeAll(Tuple template) {
		try {
			return (Collection<Tuple>) server.DoWork(method.TAKEALL, template);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Collection<Tuple> readAll(Tuple template) {
		try {
			System.out.println();
			return (Collection<Tuple>) server.DoWork(method.READALL, template);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void eventRegister(eventMode mode, eventTiming timing,
			Tuple template, Callback callback) {
		try {
			InterfaceRemoteCallback c = new RemoteCallback(callback);
			server.DoCallBack(mode, timing, template, c);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	public void debug(String prefix) {
		// TODO Auto-generated method stub

	}
}
